<?php
class ColumnWidth{
	public $w;
	public function ColumnWidth(){
		$this->w = array(
			'label_tandan'	=> 220,
			'role_detail'	=> 220,
		);
	}
}

class ColumnDetail{
	public function prepareJenisPerawatan($arr){
		$result = '<ul class="item">';
		if( count($arr) > 0 ){
			foreach($arr as $arr_v){
				$result .= '<li>'.$arr_v['jenis_perawatan'].'</li>';
			}
		}
		$result .= '</ul>';
		
		return $result;
	}
	
	public function prepareMaterial($arr){
		$result = '<ul class="item">';
		if( count($arr) > 0 ){
			foreach($arr as $arr_v){
				$result .= '<li>'.$arr_v['nama'].'('.sprintf('%.2f',$arr_v['jumlah']).' '.$arr_v['satuan'].')</li>';
			}
		}
		else{
			$result .= '<li>-</li>';
		}
		$result .= '</ul>';
		
		return $result;
	}
	
	public function preparePengirimanItem($arr){
		$result = '<ul class="item">';
		if( count($arr) > 0 ){
			foreach($arr as $arr_v){
				$result .= '<li>'.$arr_v['jml_kotak'].'('.$arr_v['jml_kecambah'].'- '.$arr_v['keterangan'].')</li>';
			}
		}
		else{
			$result .= '<li>-</li>';
		}
		$result .= '</ul>';
		
		return $result;
	}
	
	public function prepareNoTandan($arr){
		$result = '<ul class="item">';
		if( count($arr) > 0 ){
			foreach($arr as $arr_v){
				$result .= '<li>'.$arr_v['no_tandan'].'</li>';
			}
		}
		else{
			$result .= '<li>-</li>';
		}
		$result .= '</ul>';
		
		return $result;
	}
	
	public function preparePeralatan($arr){
		$result = '<ul class="item">';
		if( count($arr) > 0 ){
			foreach($arr as $arr_v){
				$result .= '<li>'.$arr_v['nama'].'('.$arr_v['jumlah'].' buah)</li>';
			}
		}
		$result .= '</ul>';
		
		return $result;
	}
	
	public function prepareLabelDanBeratTandan($arr){
		$result = '<ul class="item">';
		if( count($arr) > 0 ){
			foreach($arr as $arr_v){
				$result .= '<li>'.$arr_v['label_tandan'].'('.$arr_v['berat_tandan'].' kg)</li>';
			}
		}
		$result .= '</ul>';
		
		return $result;
	}
	
	public function prepareKelompokPembibitan($arr){
		$result = '<ul class="item">';
		if( count($arr) > 0 ){
			foreach($arr as $arr_v){
				$result .= '<li>'.$arr_v['nama'].'('.$arr_v['jumlah'].')</li>';
			}
		}
		$result .= '</ul>';
		
		return $result;
	}
	
	public function prepareRoleDetail($arr){
		$result = '<ul class="item">';
		if( count($arr) > 0 ){
			foreach($arr as $arr_v){
				$result .= '<li>'.$arr_v['subbagian'].'('.$arr_v['role'].')</li>';
			}
		}
		$result .= '</ul>';
		
		return $result;
	}
	
	public function prepareColumnContent($content, $type){
		$preparedContent = '';
		switch($type){
			case 'jenis_perawatan':
				$preparedContent = $this->prepareJenisPerawatan($content);
				break;
			case 'kelompok':
				$preparedContent = $this->prepareKelompokPembibitan($content);
				break;
			case 'material':
				$preparedContent = $this->prepareMaterial($content);
				break;
			case 'peralatan':
				$preparedContent = $this->preparePeralatan($content);
				break;
			case 'label_tandan':
				$preparedContent = $this->prepareLabelDanBeratTandan($content);
				break;
			case 'no_tandan':
				$preparedContent = $this->prepareNoTandan($content);
				break;
			case 'role_detail':
				$preparedContent = $this->prepareRoleDetail($content);
				break;
			case 'pengiriman_item':
				$preparedContent = $this->preparePengirimanItem($content);
				break;								
		}
		
		return $preparedContent;
	}
}

class GridView extends ColumnDetail{
    
	protected $canEdit;
	protected $canDelete;
	
	protected $data;
	protected $filter_exclude;

	protected $col_name;
	protected $col_title;

	protected $relative_link;
	protected $total_page;
	protected $limit;
	protected $total_record;
	protected $current_page_number;

	protected $next;
	protected $prev;
	protected $start;

	protected $result;

	protected $nosort; // field that disabled to sort
	protected $sort_by;
	protected $sort_order;

	protected $search_keyword;
	protected $search_field;
	
	public	  $col;
	
	function __construct($data=NULL, $config=array()){
		$this->col				= new ColumnWidth();
		$this->canEdit			= $this->checkEditAuthority();
		$this->canDelete		= $this->checkDeleteAuthority();
		
		$this->data 			= $data;
		$this->relative_link 	= $config['relative_link'];
		$this->col_name  		= $config['col_name'];
		$this->col_title 		= $config['col_title'];
		$this->total_record 	= $config['total_record'];
		$this->title			= $config['title'];
		$this->filter_exclude	= isset($config['filter_exclude']) ? $config['filter_exclude'] : array();
		
		$this->nosort			= isset($config['nosort']) ? $config['nosort'] : array();
		if( ($this->limit = $this->getGET('limit')) == NULL )
			$this->limit  = 50;
		$this->sort_by 			= $this->getGET('sort_by');
		$this->sort_order 		= $this->getGET('sort_order');
		$this->search_keyword	= $this->getGET('search_keyword');
		$this->search_field		= $this->getGET('search_field');
		$this->start			= $this->getGET('start') ? $this->getGET('start') : 1;
		
		$this->prev = $this->start - $this->limit;
		$this->next = $this->start + $this->limit;
		
		$this->total_page  			= ceil($this->total_record/$this->limit);
		$this->current_page_number 	= round($this->start / $this->limit) + 1;	
	}
	
	protected function checkEditAuthority(){
        if( $_SESSION['role'][$_GET['subbagian']] == 'manage' ||
            $_SESSION['role'][$_GET['subbagian']] == 'super')
            return true;
        else
            return false;
	}
	
	protected function checkDeleteAuthority(){
        if( $_SESSION['role'][$_GET['subbagian']] == 'delete' ||
            $_SESSION['role'][$_GET['subbagian']] == 'super')
            return true;
        else
            return false;
	}
	
	function getGET($param){
		if( isset( $_GET[$param] ) && $_GET[$param] != '' )
			return $_GET[$param];
		else
			return NULL;
	}
	
	function createBody(){
		$body = '
					<table cellspacing="0" cellpadding="0" border="0" style="">
						<tbody>
		';
		$i = 0;
		
		if( count($this->data) > 0 ){
			foreach( $this->data as $d ){
				if( $i%2 )
					$body .= '<tr>';
				else
					$body .= '<tr class="erow">';

				for($j=0; $j<count($this->col_title); $j++){
					$c     	 = $this->col_name[$j];
					$content = $d[$c];
					$temp	 = '';
					if( is_array($content)){
						if( count($content) > 0 )
							$content = $this->prepareColumnContent($content, $c);
						else
							$content = '';
					}
					
					$width  = isset($this->col->w[$c]) ? $this->col->w[$c] : 130;
			
					$body .= '<td class="'.($this->sort_by==$c? "sorted" : "").'"><div style="text-align: center; width: '.$width.'px;">'.$content.'</div></td>';
				}
				
				$th_operation = '';
				if( $this->canEdit || $this->canDelete ){
                    $th_operation = '<td class=""><div style="text-align: center; width: 100px;">';
                    if( $this->canEdit )
						$th_operation .= '<a class="operation edit" href="index.php?action=edit&bagian='.$_GET['bagian'].'&subbagian='.$_GET['subbagian'].'&id='.$d['id'].'">Edit</a>';
						
					if( $this->canEdit && $this->canDelete )
						$th_operation .= ' ';
					
					if( $this->canDelete )
						$th_operation .= '<a class="operation delete" href="index.php?action=delete&bagian='.$_GET['bagian'].'&subbagian='.$_GET['subbagian'].'&id='.$d['id'].'">Delete</a>';
                    $th_operation .= '</div></td>';
                }
				
				$body .= $th_operation;
				
				$body .= '</tr>';
				$i++;
			}
		}
		else
			$body .= '<tr><td colspan="'.count($this->col_title).'">No data</td></tr>';
			$body .= '
						</tbody>
					</table>
				</div>
		';
		
		return $body;
	}	
	
	function createFilterForm(){
		$filter = '
			<div class="sDiv" style="display: block;">
				<div class="sDiv2">
					<span style="clear:left; float:left; padding:4px 1px;">Quick Search&nbsp;</span>
					<form method="GET" action="'.$this->relative_link.'">
						<input type="hidden" name="action" value="'.$_GET['action'].'" />
						<input type="hidden" name="bagian" value="'.$_GET['bagian'].'" />
						<input type="hidden" name="subbagian" value="'.$_GET['subbagian'].'" />
						<input type="text" class="qsbox" name="search_keyword" value="'.$this->search_keyword.'" size="30"/>
						<select name="search_field">
			';

			for($i=0; $i<count($this->col_title); $i++){
				if( !in_array($this->col_name[$i], $this->filter_exclude) ){
					$selected = $this->col_name[$i] == $this->search_field ? 'selected="selected"' : '';
					$filter .= "<option value=\"{$this->col_name[$i]}\" $selected>{$this->col_title[$i]}</option>";					
				}
			}

			$filter .= '
						</select>
						<input type="submit" value="Search"/>
						<input type="button" value="Reset" onclick="javascript:window.location.assign(\''.$this->relative_link.'\');"/>
					</form>
				</div>
			</div>
		';

		return $filter;
	}
	
	protected function createHeader(){
		$header = '';
		// header, column sorting..
		$header .= '
			<div class="flexigrid">
				<div class="mDiv"><div class="" style="color:#333;">'.$this->title.'</div></div>
				<div class="bDiv">
				<div class="hDiv">
					<table cellspacing="0" cellpadding="0">
						<thead>
							<tr>
							 ';
		for($i=0; $i<count($this->col_title); $i++){
			$t = $this->col_title[$i];
			$c = $this->col_name[$i];
			
			$th_class  = $this->sort_by==$c? "sorted" : "";
			$div_class = $this->sort_by==$c ? ($this->sort_order=='asc' ? "sasc" : "sdesc" ) : "";
			$a_asc  = $this->relative_link.'&start=0&sort_by='.$c.'&sort_order=asc&search_keyword='.$this->search_keyword.'&search_field='.$this->search_field;
			$a_desc = $this->relative_link.'&start=0&sort_by='.$c.'&sort_order=desc&search_keyword='.$this->search_keyword.'&search_field='.$this->search_field;
			
			$width  = isset($this->col->w[$c]) ? $this->col->w[$c] : 130;
			
			if( in_array($c, $this->nosort) ){
				$header 	.= '<th class="'.$th_class.'" align="center" style="color:#444;">
									<div class="'.$div_class.'" style="text-align: center; width: '.$width.'px;">
										'.$t.'
									</div>
								</th>';
			}
			else{
				$header 	.= '<th class="'.$th_class.'" align="center" style="color:#444;">
									<div class="'.$div_class.'" style="text-align: center; width: '.$width.'px;">
										'.$t.'<BR/><a href="'.$a_asc.'"><img src="image/grid/arrow_up.gif" title="ascending"/></a>
										<a href="'.$a_desc.'"><img src="image/grid/arrow_down.gif" title="descending"/></a>
									</div>
								</th>';
			}
		}
		
		$th_operation = '';
		if( $this->canEdit || $this->canDelete ){
			$th_operation = '<th class="" align="center" style="color:#444;">
								<div class="" style="text-align: center; width: 100px;">Operation</div>
							 </th>';
		}
		$header .= $th_operation;
		$header .= '		</tr>
						</thead>
					</table>
				</div>
		';

		return $header;
	}
	
	function createFooter(){
		$link = '
			<script language="JavaScript">
				function openDir( form ) {
					var newIndex = form.page.selectedIndex;

					if ( newIndex < 0 )
						alert( "Please select a location!" );
					else {
						cururl = form.page.options[ newIndex ].value;
						window.location.assign( cururl );
					}
				}
			</script>

			<div class="pDiv">
				<div class="pDiv2">
					<div class="pGroup">
						<span style="float:left; padding:4px;">Goto Page</span>
						<form>
						<select name="page" size="1" onChange="openDir( this.form )">
						';

			for($offset=0, $number=1;$offset < $this->total_record;$offset+=$this->limit, $number++){
				if( $offset != $this->start )
					$link .= "<option value=\"$this->relative_link&amp;start=$offset&amp;sort_by=$this->sort_by&amp;sort_order=$this->sort_order&amp;search_keyword=$this->search_keyword&amp;search_field=$this->search_field\">$number </option> ";
				else
					$link .= "<option selected=\"selected\">$number </option> ";
			}
		
		// Prepare buttons
		$buttonFirst = '';
		$buttonPrev  = '';
		$buttonNext  = '';
		$buttonLast  = '';
		
		if( $this->start == 1 ){
			// First Page, disable prev and first button
			$buttonFirst = '<div class="pFirst_disable pButton"><span/></div>';
			$buttonPrev  = '<div class="pPrev_disable pButton"><span/></div>';
		}
		else{
			$buttonFirst = '<div class="pFirst pButton"><a href="'.$this->relative_link.'&amp;start=0&amp;sort_by='.$this->sort_by.'&amp;sort_order='.$this->sort_order.'&amp;search_keyword='.$this->search_keyword.'&amp;search_field='.$this->search_field.'"><span/></a></div>';
			$buttonPrev  = '<div class="pPrev pButton"><a href="'.$this->relative_link.'&amp;start='.$this->prev.'&amp;sort_by='.$this->sort_by.'&amp;sort_order='.$this->sort_order.'&amp;search_keyword='.$this->search_keyword.'&amp;search_field='.$this->search_field.'"><span/></a></div>';
		}
		
		if( $this->next > $this->total_record ){
			// Last page, disable next and last button
			$buttonNext  = '<div class="pNext_disable pButton"><span/></div>';
			$buttonLast  = '<div class="pLast_disable pButton"><span/></div>';
		}
		else{
			$buttonNext  = '<div class="pNext pButton"><a href="'.$this->relative_link.'&amp;start='.$this->next.'&amp;sort_by='.$this->sort_by.'&amp;sort_order='.$this->sort_order.'&amp;search_keyword='.$this->search_keyword.'&amp;search_field='.$this->search_field.'"><span/></a></div>';
			$buttonLast  = '<div class="pLast pButton"><a href="'.$this->relative_link.'&amp;start='.(($this->total_page-1)*$this->limit).'&amp;sort_by='.$this->sort_by.'&amp;sort_order='.$this->sort_order.'&amp;search_keyword='.$this->search_keyword.'&amp;search_field='.$this->search_field.'"><span/></a></div>';
		}
		
		$link .= '
						</select>
						</form>
						<span />
					</div>
					<!--<div style="float:left; width:40px; padding:3px;"></div>-->
					<div class="btnseparator"></div>
					<div class="pGroup">						
						'.$buttonFirst.'						
						'.$buttonPrev.'
					</div>
					<div class="btnseparator"></div>
					<div class="pGroup">
						<span class="pcontrol">
							Page <input type="text" value="'.$this->current_page_number.'" size="4" disabled="disabled"/> of <span>'.$this->total_page.'</span>
						</span>
					</div>
					<div class="btnseparator"></div>
					<div class="pGroup">						
						'.$buttonNext.'
						'.$buttonLast.'
					</div>
					<div class="btnseparator"></div>
					<div class="pGroup">
						<span class="pPageStat">Displaying '.$this->start.' to '.min(($this->start+$this->limit-1), $this->total_record).' of '.$this->total_record.' items</span>
					</div>
				</div>
			</div>
		</div>
		';

		return $link;
	}
    
    private function insertScript(){
        $script  = '';
        $script .= '<script language="javascript">';
        $script .= "
        $(document).ready(function(){
           // confirm on delete
           $('a.delete').click(function(){
                return confirm('Hapus Data?');
           });
           
           // confirm on edit
           $('a.edit').click(function(){
                return confirm('Edit Data?');
           });
        });
        ";
        $script .= '</script>';
        
        return $script;
    }
	
	public function create(){
		echo $this->createHeader();
		echo $this->createBody();
		echo $this->createFilterForm();
		echo $this->createFooter();
        echo $this->insertScript();
	}
}

?>